package cn.chendd.shiro.examples.commponent;

import ch.qos.logback.access.jetty.RequestLogImpl;
import cn.chendd.shiro.examples.enums.EnumLoginFail;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * @author chendd
 * @date 2019/6/15 18:19
 * 1、自定义登录Form的用户名、密码等参数；
 * 2、增加验证码校验的功能
 */
public class CustomLoginFormFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest req, ServletResponse resp) throws Exception {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String sessionValidCode = (String) request.getSession().getAttribute("sessionValidCode");
        System.out.println(request + "-------" + sessionValidCode);
        //取出来后无论是否登录成功，都过期验证码的session
        request.getSession().removeAttribute("sessionValidCode");
        String validCode = request.getParameter("validCode");
        if(StringUtils.hasLength(sessionValidCode) && !sessionValidCode.equalsIgnoreCase(validCode)){
            request.setAttribute(CustomLoginFormFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME , EnumLoginFail.ValidCodeError.getKey());
            return true;
        }
        return super.onAccessDenied(request, response);
    }

    /*可使用此方法恒定返回到主页地址*/
    /*@Override
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        System.out.println("shiroFilter: " + "/index" + "---" + getSuccessUrl());
        WebUtils.redirectToSavedRequest(request, response, getSuccessUrl());
    }*/
}
